package logic

import (
	"api/pkg"
	"context"
	"github.com/google/uuid"
	"goods-srv/goods"
	"order-srv/model/redis"
	"order-srv/order"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGenerateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateOrderLogic {
	return &GenerateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GenerateOrderLogic) GenerateOrder(req *types.GenerateOrderRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	detail, err := l.svcCtx.GoodsSrv.GoodsDetail(l.ctx, &goods.GoodsDetailRequest{GoodsId: req.GoodsId})
	if err != nil || detail.ID == 0 {
		return &types.Response{
			Code:    -1,
			Message: "商品查询失败",
			Data:    nil,
		}, nil
	}
	value := l.ctx.Value("userId").(string)
	userId, _ := strconv.Atoi(value)
	total := float32(req.GoodsNum) * detail.GoodsPrice
	generateOrder, err := l.svcCtx.OrderSrv.GenerateOrder(l.ctx, &order.GenerateOrderRequest{
		UserId:  int64(userId),
		OrderSn: uuid.NewString(),
		Total:   total,
	})
	if err != nil || generateOrder.OrderId == 0 {
		return &types.Response{
			Code:    -2,
			Message: "生成订单失败",
			Data:    nil,
		}, nil
	}
	orderGoods, err := l.svcCtx.OrderSrv.GenerateOrderGoods(l.ctx, &order.GenerateOrderGoodsRequest{
		UserId:       int64(userId),
		OrderId:      generateOrder.OrderId,
		GoodsId:      req.GoodsId,
		OrderGoodsSn: uuid.NewString(),
		GoodsTitle:   detail.GoodsTitle,
		GoodsPrice:   detail.GoodsPrice,
		GoodsNum:     req.GoodsNum,
	})
	if err != nil || orderGoods.OrderGoodsId == 0 {
		return &types.Response{
			Code:    -3,
			Message: "生成订单商品失败",
			Data:    nil,
		}, nil
	}
	err = redis.RemoveGoodsStock(req.GoodsId, req.GoodsNum)
	if err != nil {
		return nil, err
	}
	itoa := strconv.Itoa(int(total))
	alipay := pkg.Alipay(detail.GoodsTitle, uuid.NewString(), itoa)
	return &types.Response{
		Code:    0,
		Message: "生成订单成功",
		Data: map[string]interface{}{
			"url": alipay,
		},
	}, nil
}
